package com.cjr.mq.complex;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SendAndConfirm {

    @Autowired
    RabbitTemplate rabbitTemplate;

    public void sendConfirm(String msg){
        CorrelationData correlationData = new CorrelationData("消息唯一标识符");
        rabbitTemplate.convertAndSend(RabbitConfig1.EXCHANGE,null,msg,correlationData);
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("Confirm方法执行了");
                System.out.println("打印："+correlationData.getId());
                if(ack==true){
                    System.out.println("消息成功发送，订单入库，更改订单状态");
                }else {
                    System.out.println("消息接收失败，可以在这里进行失败的业务处理"+cause);
                }
            }
        });
    }

    public void sendReturn(){
        rabbitTemplate.convertAndSend(RabbitConfig1.EXCHANGE,null,"return返回模式");
        log.info("消息发送完毕。");
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("被退回的消息为：{}", message);
                log.info("错误码：{}", replyCode);
                log.info("错误信息：{}", replyText);
                log.info("交换机：{}", exchange);
                log.info("路由key：{}", routingKey);
            }
        });
    }

    public void onlySend(String msg){
        rabbitTemplate.convertAndSend(RabbitConfig1.EXCHANGE,null,msg);
    }


}
